package com.hzf.wxplatform.web.controller.manager.order;

import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.util.*;
import com.hzf.designer.dao.model.DneedsDemand;
import com.hzf.designer.dao.model.DneedsDemandExample;
import com.hzf.material.dao.model.*;
import com.hzf.order.dao.model.*;
import com.hzf.ucenter.dao.model.UcenterUser;
import com.hzf.ucenter.dao.model.UcenterUserOauth;
import com.hzf.ucenter.dao.model.UcenterUserOauthExample;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.hzf.wxplatform.common.utils.WxGetGpsUtils;
import com.jpay.ext.kit.IpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.jpay.ext.kit.IpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.ext.kit.ZxingKit;
import com.jpay.vo.AjaxResult;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApi.TradeType;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfig.PayModel;
import com.jpay.weixin.api.WxPayApiConfigKit;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * describe: TODO
 * creat_user: 白开水
 * creat_time: 2017/12/11   9:36
 **/
@Controller
@RequestMapping("/orderUser")
public class OrderUserController extends BaseController {
    @Autowired
    ApiService apiService;

    String appid = PropertiesFileUtil.getInstance("wx").get("wx_appid");
    String mch_id = "1357612802";
    String partnerKey = "EYZHrw8oTEnJFTAXDqPt6Onjg8umV2mR";
    public WxPayApiConfig getApiConfig() {
        WxPayApiConfig apiConfig = WxPayApiConfig.New()
                .setAppId(appid)
                .setMchId(mch_id)
                .setPaternerKey(partnerKey)
                .setPayModel(PayModel.BUSINESSMODEL);
        return apiConfig;
    }
    @RequestMapping(value = "/orderAdd")
    @ResponseBody
    public Object orderAdd(Model model, HttpServletRequest httpServletRequest,String type) throws  Exception{
        String detile = "";


        byte[] a = UcenterUserUtils.getUser(httpServletRequest.getSession());
        System.out.println(type);
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a);
        if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        detile="会装房购买材料"+user.getUserName();
        UcenterUserOauthExample ucenterUserOauthExample = new UcenterUserOauthExample();
        ucenterUserOauthExample.createCriteria().andIdEqualTo(user.getUserThirdId());
        UcenterUserOauth ucenterUserOauth =apiService.selectOauthEx(ucenterUserOauthExample);
        List<OrderCart> list= new ArrayList<>();
        if(type.equals("0")) {
            list = (List<OrderCart>) EhCacheUtil.get("hzf-wxplatform-web-ehcache", user.getId() + "dingdanList");
        }else if(type.equals("1")){
            OrderCart orderCart =(OrderCart) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhijiedingdan");
            List<OrderCart> carts = new ArrayList<>();
            OrderCart orderCart1 =new OrderCart();
            orderCart1.setShopId(orderCart.getShopId());
            carts.add(orderCart);
            orderCart1.setGoods(carts);
            list.add(orderCart1);
        }
        if(type.equals("0")||type.equals("1")||type.equals("2")){
            double price = 0.00;
            for(OrderCart orderCart:list){
                for(OrderCart orderCart1 :orderCart.getGoods()){
                    OrderUserInfoExample example = new OrderUserInfoExample();
                    example.createCriteria().andGoodsIdEqualTo(orderCart1.getGoodsId()).andModelIdEqualTo(orderCart1.getModelId()).andUserIdEqualTo(user.getId());
                    List<OrderUserInfo> orderUserinfos=apiService.selectOrderInfoList(example);
                    if(0!=orderUserinfos.size()){
                        System.out.println("122312");
                        return new WxplatformResult(WxplatformResultConstant.FAILED, null);
                    }
                    if(orderCart1.getInstallId()==1){
                        double jiage = orderCart1.getModel().getPrice()*orderCart1.getCount();
                        double installPrice = orderCart1.getCount()*orderCart1.getMaterialGoods().getInstallPrice();
                        double heji=Arith.add(jiage,installPrice);
                        price= Arith.add(price,heji);
                    }else{
                        double jiage = orderCart1.getModel().getPrice()*orderCart1.getCount();
                        price= Arith.add(jiage,price);
                    }
                }
            }
            OrderUserAddress address = (OrderUserAddress) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi");
            OrderUser orderUser = new OrderUser();
            orderUser.setAddress(address.getAddress());
            orderUser.setPhone(address.getPhone());
            orderUser.setOrderPayId(WeixinUtil.getRandomString(32));
            orderUser.setPayPrice(price);
            orderUser.setCreateTime(new Date());
            orderUser.setPayState(0);
            orderUser.setUserId(user.getId());
            orderUser.setUserName(address.getUserName());
            orderUser.setOrderState(0);
            orderUser=apiService.inserllOrder(orderUser);
            OrderUserInfo orderUserInfo = new OrderUserInfo();
            for(OrderCart orderCart:list){
                for(OrderCart orderCart1 :orderCart.getGoods()){

                    orderUserInfo.setCount(orderCart1.getCount());
                    orderUserInfo.setGoodsId(orderCart1.getGoodsId());
                    orderUserInfo.setModelId(orderCart1.getModelId());
                    orderUserInfo.setOrderUserId(orderUser.getId());
                    orderUserInfo.setUserId(user.getId());
                    if(orderCart1.getInstallId()==1){
                        double jiage = orderCart1.getModel().getPrice()*orderCart1.getCount();
                        double installPrice = orderCart1.getCount()*orderCart1.getMaterialGoods().getInstallPrice();
                        double price1= Arith.add(jiage,installPrice);
                        orderUserInfo.setDistributionFee(installPrice);
                        orderUserInfo.setPrice(price1);
                    }else{
                        double price1= orderCart1.getModel().getPrice()*orderCart1.getCount();
                        orderUserInfo.setDistributionFee(0.00);
                        orderUserInfo.setPrice(price1);

                    }
                    orderUserInfo.setCreateTime(System.currentTimeMillis());
                    orderUserInfo.setPayState(0);
                    orderUserInfo.setShopId(orderCart1.getShopId());
                    orderUserInfo.setReceivingState(0);
                    apiService.inserllOrderInfo(orderUserInfo);
                }
            }
            // openId，采用 网页授权获取 access_token API：SnsAccessTokenApi获取

            String openId = ucenterUserOauth.getOpenId();
            System.out.println(orderUser.getPayPrice()+"转换分之前");

            String total_fee=WeixinUtil.yuanToFen(orderUser.getPayPrice());
            System.out.println(total_fee+"转换分之后");
            String ip =  WxGetGpsUtils.getLocalIp(httpServletRequest);
            getApiConfig();
            Map<String, String> params = getWxPayApiConfig()
                    .setAttach(detile)
                    .setBody(detile)
                    .setOpenId(openId)
                    .setSpbillCreateIp(ip)
                    .setTotalFee("1")
                    .setTradeType(WxPayApi.TradeType.JSAPI)
                    .setNotifyUrl("http://hzf.nat100.top/pay/orderNotify")
                    .setOutTradeNo(orderUser.getId()+"")
                    .build();
            System.out.println(params.toString());
            String xmlResult = WeixinUtil.toPaySign(params);
            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
            System.out.println(result);
            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            String result_code = result.get("result_code");
            String prepay_id = result.get("prepay_id");
            Map<String, String> packageParams = WeixinUtil.prepayIdCreateSign(prepay_id);
            if(null!= EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhifu")){
                EhCacheUtil.remove("hzf-wxplatform-web-ehcache",user.getId()+"zhifu");
                EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"zhifu",packageParams);
            }else{
                EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"zhifu",packageParams);

            }
            return new WxplatformResult(WxplatformResultConstant.SUCCESS, packageParams);

        }else if(type.equals("3")){

            OrderUserAddress address = (OrderUserAddress) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi");
            OrderUser orderUser = (OrderUser)EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"xiugaidingdan");
            orderUser.setAddress(address.getAddress());
            orderUser.setUserName(address.getUserName());
            orderUser.setPhone(address.getPhone());
            apiService.updateOrder(orderUser);

            String openId = ucenterUserOauth.getOpenId();
            System.out.println(orderUser.getPayPrice()+"转换分之前");

            String total_fee=WeixinUtil.yuanToFen(orderUser.getPayPrice());
            System.out.println(total_fee+"转换分之后");
            String ip =  WxGetGpsUtils.getLocalIp(httpServletRequest);
            getApiConfig();
            Map<String, String> params = getWxPayApiConfig()
                    .setAttach(detile)
                    .setBody(detile)
                    .setOpenId(openId)
                    .setSpbillCreateIp(ip)
                    .setTotalFee("1")
                    .setTradeType(WxPayApi.TradeType.JSAPI)
                    .setNotifyUrl("http://hzf.nat100.top/pay/orderNotify")
                    .setOutTradeNo(orderUser.getId()+"")
                    .build();
            System.out.println(params.toString());
            String xmlResult = WeixinUtil.toPaySign(params);
            Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
            System.out.println(result);
            String return_code = result.get("return_code");
            String return_msg = result.get("return_msg");
            String result_code = result.get("result_code");
            String prepay_id = result.get("prepay_id");
            Map<String, String> packageParams = WeixinUtil.prepayIdCreateSign(prepay_id);
            if(null!= EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhifu")){
                EhCacheUtil.remove("hzf-wxplatform-web-ehcache",user.getId()+"zhifu");
                EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"zhifu",packageParams);
            }else{
                EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"zhifu",packageParams);

            }
            return new WxplatformResult(WxplatformResultConstant.SUCCESS, packageParams);
        }

return null;


    }
    @RequestMapping(value = "/saveOrder", method = RequestMethod.POST)
    @ResponseBody
    private Object saveCart(Model model, OrderCart orderCart, HttpServletRequest httpServletRequest) {
        String ip =  WxGetGpsUtils.getLocalIp(httpServletRequest);
        System.out.println(ip);
        byte[] a = UcenterUserUtils.getUser(httpServletRequest.getSession());
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a); if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        orderCart.setUserId(user.getId());
        if(null!=EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhijiedingdan")){
            EhCacheUtil.remove("hzf-wxplatform-web-ehcache",user.getId()+"zhijiedingdan");
        }
        EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"zhijiedingdan", orderCart);
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, "直接订单");
    }
    @RequestMapping(value="/orderQr",method = RequestMethod.GET)
    private String orderQr(Model model,HttpServletRequest request){
        String ip =  WxGetGpsUtils.getLocalIp(request);
        System.out.println(ip);
        byte[] a = UcenterUserUtils.getUser(request.getSession());
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a); if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        OrderCart orderCart =(OrderCart) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhijiedingdan");
        MaterialShop materialShop = new MaterialShop();
        MaterialShopExample example = new MaterialShopExample();
        example.createCriteria().andShopIdEqualTo(orderCart.getShopId());
        materialShop= apiService.selectByShop(example);
        orderCart.setShops(materialShop);
        MaterialGoods materialGoods = new MaterialGoods();
        MaterialGoodsExample materialGoodsExample = new MaterialGoodsExample();
        materialGoodsExample.createCriteria().andGoodsIdEqualTo(orderCart.getGoodsId());
        materialGoods = apiService.selectByGoods(materialGoodsExample);
        MaterialGoodsModelExample materialGoodsModelExample = new MaterialGoodsModelExample();
        materialGoodsModelExample.createCriteria().andModelIdEqualTo(orderCart.getModelId());
        List<MaterialGoodsModel> list =apiService.selectByMaterialGoodsModel(materialGoodsModelExample);;
        MaterialGoodsModel materialGoodsModel = list.get(0);
        orderCart.setMaterialGoods(materialGoods);
        orderCart.setShops(materialShop);
        orderCart.setModel(materialGoodsModel);
        orderCart.setShopName(materialShop.getShopName());
        model.addAttribute("orderCart",orderCart);
        double price = 0.00;
        if (orderCart.getInstallId() == 1) {
            double shangpinPrice =  materialGoodsModel.getPrice()*orderCart.getCount();
            double anzhuangPrice = materialGoods.getInstallPrice()*orderCart.getCount();
            price =Arith.add(shangpinPrice,anzhuangPrice);
        }else{
            price =  materialGoodsModel.getPrice()*orderCart.getCount();

        }

        OrderUserAddress address = new OrderUserAddress();
        if(null!=EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi")){
            address=(OrderUserAddress) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi");
        }
        model.addAttribute("address", address);
        model.addAttribute("zongjia", price);
        model.addAttribute("shuliang", "1");
        return  thymeleaf("/YZ/YZ_ORDER_TijiaoTick");

    }
    @RequestMapping (value = "/toPay",method = RequestMethod.GET)
    public String toPay(Model model,HttpServletRequest servletRequest){
        String ip =  WxGetGpsUtils.getLocalIp(servletRequest);
        System.out.println(ip);
        byte[] a = UcenterUserUtils.getUser(servletRequest.getSession());
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a); if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        Map<String, String> packageParams= (Map<String, String>) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"zhifu");
        model.addAttribute("data",packageParams);
        return thymeleaf("/YZ/YZPAYQR");
    }
    @RequestMapping (value = "/toWxDemandPay",method = RequestMethod.GET)
    public String toWxDemandPay(Model model,HttpServletRequest servletRequest){
        String ip =  WxGetGpsUtils.getLocalIp(servletRequest);
        System.out.println(ip);
        byte[] a = UcenterUserUtils.getUser(servletRequest.getSession());
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a); if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        Map<String, String> packageParams= (Map<String, String>) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"demendzhifu");
        model.addAttribute("data",packageParams);
        return thymeleaf("/YZ/YZPAYQR");
    }
    @RequestMapping (value = "/orderToPay",method = RequestMethod.GET)
    public String orderToPay (Model model,HttpServletRequest servletRequest,int id){
        byte[] a = UcenterUserUtils.getUser(servletRequest.getSession());
        String ip =  WxGetGpsUtils.getLocalIp(servletRequest);
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a);
        if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        OrderUserExample orderUserExample = new OrderUserExample();
        orderUserExample.createCriteria().andUserIdEqualTo(user.getId()).andIdEqualTo(id).andOrderStateEqualTo(0);
        OrderUser orderUser = apiService.selectOrder(orderUserExample);
        if (null==orderUser){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        List<OrderUserInfo> list =apiService.selectByUserByOrderUser(orderUser.getId());
        OrderUserAddress address = new OrderUserAddress();
        if(null!=EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi")){
            address=(OrderUserAddress) EhCacheUtil.get("hzf-wxplatform-web-ehcache",user.getId()+"dizhi");
        }else{
            OrderUserAddressExample example = new OrderUserAddressExample();
            example.createCriteria().andAddressEqualTo(orderUser.getAddress()).andUserIdEqualTo(orderUser.getUserId());
            List<OrderUserAddress> list1=apiService.selectExample(example);
            if(null!=list1){
                address = list1.get(0);
            }
            EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"dizhi", address);

        }
        orderUser.setOrderUserInfoList(list);
        EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"xiugaidingdan", orderUser);

        model.addAttribute("address",address);
        model.addAttribute("zongjia",orderUser.getPayPrice());
        model.addAttribute("data",orderUser);
        model.addAttribute("shuliang", list.size());
        return thymeleaf("/YZ/YZ_ORDER_OrderTick");
    }
    @RequestMapping(value="/toDemandPay",method = RequestMethod.POST)
    @ResponseBody
    private Object toDemandPay(Model model,HttpServletRequest request,int id) throws  Exception{
        byte[] a = UcenterUserUtils.getUser(request.getSession());
        UcenterUser user = (UcenterUser) ByteUtils.ByteToObject(a); if(null==user){
            model.addAttribute("data","您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return  thymeleaf("/404");
        }
        String detile="会装房选标设计师"+user.getUserName();

        UcenterUserOauthExample ucenterUserOauthExample = new UcenterUserOauthExample();
        ucenterUserOauthExample.createCriteria().andIdEqualTo(user.getUserThirdId());
        UcenterUserOauth ucenterUserOauth = apiService.selectOauthEx(ucenterUserOauthExample);
        DneedsDemandExample dneedsDemandExample = new DneedsDemandExample();
        dneedsDemandExample.createCriteria().andIdEqualTo(id).andUserIdEqualTo(user.getId());
        DneedsDemand dneedsDemand = apiService.getDneedsDemand(dneedsDemandExample);
        OrderUserDemandExample example = new OrderUserDemandExample();
        example.createCriteria().andDemandIdEqualTo(dneedsDemand.getId());
        OrderUserDemand orderUserDemand = apiService.getOrderUserDemand(example);
        OrderUserExample orderUserExample = new OrderUserExample();
        orderUserExample.createCriteria().andIdEqualTo(orderUserDemand.getOrderUserId());
        OrderUser orderUser =apiService.selectOrder(orderUserExample);


        String openId = ucenterUserOauth.getOpenId();
        System.out.println(orderUser.getPayPrice()+"转换分之前");

        String total_fee=WeixinUtil.yuanToFen(orderUser.getPayPrice());
        System.out.println(total_fee+"转换分之后");
        String ip =  WxGetGpsUtils.getLocalIp(request);
        getApiConfig();
        Map<String, String> params = getWxPayApiConfig()
                .setAttach(detile)
                .setBody(detile)
                .setOpenId(openId)
                .setSpbillCreateIp(ip)
                .setTotalFee("1")
                .setTradeType(WxPayApi.TradeType.JSAPI)
                .setNotifyUrl("http://hzf.nat100.top/pay/orderNotify")
                .setOutTradeNo(orderUser.getId()+"")
                .build();
        System.out.println(params.toString());
        String xmlResult = WeixinUtil.toPaySign(params);
        Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
        System.out.println(result);
        String return_code = result.get("return_code");
        String return_msg = result.get("return_msg");
        String result_code = result.get("result_code");
        String prepay_id = result.get("prepay_id");
        Map<String, String> packageParams = WeixinUtil.prepayIdCreateSign(prepay_id);
        EhCacheUtil.put("hzf-wxplatform-web-ehcache",user.getId()+"demendzhifu",packageParams);

        return new WxplatformResult(WxplatformResultConstant.SUCCESS, packageParams);

    }

    public WxPayApiConfig getWxPayApiConfig() {
        WxPayApiConfig apiConfig = WxPayApiConfig.New()
                .setAppId(appid)
                .setMchId(mch_id)
                .setPaternerKey(partnerKey)
                .setPayModel(WxPayApiConfig.PayModel.BUSINESSMODEL);
        return apiConfig;    }
}
